import {
  Injectable,
  CanActivate,
  ExecutionContext,
  Logger,
  ForbiddenException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Repository } from 'typeorm';
import { Role } from './entities/role.entity';
import { InjectRepository } from '@nestjs/typeorm';

@Injectable()
export class RolesGuard implements CanActivate {
  private logger = new Logger('RolesGuard');

  constructor(
    private reflector: Reflector,
    @InjectRepository(Role) private readonly roleRepository: Repository<Role>,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const requiredRoles = this.reflector.get<string[]>(
      'roles',
      context.getHandler(),
    );

    this.logger.log('@@@@ 路由需要的权限', requiredRoles);

    if (!requiredRoles) {
      return true;
    }
    const request = context.switchToHttp().getRequest();
    const user = request.user;
    // 查询用户的权限
    if (user.roleId) {
      const roles = await this.roleRepository.findOneBy({ id: user.roleId });
      this.logger.log('@@@@ 用户权限', roles);
      if (requiredRoles.includes(roles.type)) {
        return true;
      } else {
        throw new ForbiddenException('用户没有权限进行操作');
        return false;
      }
    } else {
      this.logger.log('@@@@ 没有用户roleId', user);
      throw new ForbiddenException('没有用户roleId');
      return false;
    }
  }
}
